﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Coding4Fun.MissionControl.WP.Misc;
using Coding4Fun.MissionControl.WP.ViewModels;
using Coding4Fun.Toolkit.Storage;
using Coding4Fun.MissionControl.WP.Models;

namespace Coding4Fun.MissionControl.WP.Views
{
    public partial class AddServerPage : PhoneApplicationPage
    {
        public AddServerPage()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AttemptAddService();
        }

        private void AttemptAddService()
        {
            if (!string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtLocation.Text))
            {
                Server server = new Server
                    {
                        Name = txtName.Text,
                        Location = txtLocation.Text,
                        ImageURL = !string.IsNullOrWhiteSpace(txtAvatar.Text) ? txtAvatar.Text : string.Empty
                    };

                if (!CollectionHelper.CheckServerExists(server))
                {
                    MainPageViewModel.Instance.Servers.Add(server);

                    Serialize.Save(Constants.SERVERS_FILE, MainPageViewModel.Instance.Servers);
                    NavigationService.GoBack();
                }
                else
                {
                    Alert.Send("The service with this name or location is already registered.");
                }
            }
            else
            {
                Alert.Send("The service needs a name and a location.");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            txtName.Focus();
        }

        private void txtName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                txtLocation.Focus();
        }

        private void txtLocation_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
                txtAvatar.Focus();
        }

        private void txtAvatar_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            AttemptAddService();
        }
    }
}